import dt from '@dt/dt'
import { defineStore } from 'pinia'

import server from '@/config/server/index.js'

let api = {
  cityList: server.api().post('/api/v1/city/list')
}

function cityList(info) {
  return api.cityList.fetch(info)
}

const key_city = 'city_info'

export const cityStore = defineStore('city', {
  state: () => {
    return {
      info: dt.storage.get(key_city) || { prov: '上海', city: '上海' },
      city: null,
      citys: null,
      areas: null,
      provs: null,
      prov: null,
      area: null
    }
  },
  getters: {
    isReady: (state) => {
      return state.citys
    }
  },
  actions: {
    update() {
      cityList({}).then((res) => {
        this.provs = res
        res.some((itm, idx) => {
          if (itm.cityName.indexOf(this.info.prov) >= 0) {
            this.prov = itm
            cityList({ parentCode: itm.cityCode }).then((res) => {
              this.citys = res
              res.some((city) => {
                if (city.cityName.indexOf(this.info.city) >= 0) {
                  this.city = city
                  this.provs.splice(idx, 1)
                  this.provs.unshift(itm)
                  cityList({ parentCode: city.cityCode }).then((res) => {
                    this.areas = res
                  })
                  return true
                }
              })
            })
            return true
          }
        })
      })
    },
    select(item) {
      return new Promise((resolve, reject) => {
        if (item.level == 2) {
          if (item.cityCode == this.prov.cityCode) {
            resolve({ citys: this.citys, city: this.city })
          } else {
            cityList({ parentCode: item.cityCode }).then((res) => {
              resolve({ citys: res, city: res[0] })
            }, reject)
          }
        } else {
          if (item.cityCode == this.city.cityCode) {
            resolve({ areas: this.areas, area: this.area || this.areas[0] })
          } else {
            cityList({ parentCode: item.cityCode }).then((res) => {
              resolve({ areas: res, area: res[0] })
            }, reject)
          }
        }
      })
    },
    choice(prov, citys, city) {
      this.prov = prov
      this.citys = citys
      this.city = city
      cityList({ parentCode: city.cityCode }).then((res) => {
        this.areas = res
      })
      dt.storage.set(key_city, { prov: prov.cityName, city: city.cityName })
    }
  }
})
